#include "server.h"

void transfer(char* buf)
{
	char srcPath[PATH_LEN] = {},destPath[PATH_LEN] = {};

	sprintf(srcPath,"%s%s",ACC_PATH,ctos.acc.bank);
	sprintf(destPath,"%s%s",ACC_PATH,ctos.acc.IdCard);

	//判断银行卡号是否正确
	if(0 != access(destPath,F_OK))
	{
		sprintf(buf,"N:目标卡号不存在，请检查!");
		return;
	}

	int srcFd = open(srcPath,O_RDWR);
	int destFd = open(destPath,O_RDWR);
	if(0 > srcFd || 0 > destFd)
	{
		error("open");
		sprintf(buf,"N:服务器正在升级，转账失败");
		return;
	}

	Acc srcAcc = {},destAcc = {};
	read(srcFd,&srcAcc,sizeof(Acc));
	read(destFd,&destAcc,sizeof(Acc));

	if(srcAcc.balance < ctos.acc.balance)
	{
		sprintf(buf,"N:余额不足，转账失败!当前余额为：%g",srcAcc.balance);
		return;
	}

	srcAcc.balance -= ctos.acc.balance;
	destAcc.balance += ctos.acc.balance;

	lseek(srcFd,0,SEEK_SET);
	lseek(destFd,0,SEEK_SET);
	write(srcFd,&srcAcc,sizeof(Acc));
	write(destFd,&destAcc,sizeof(Acc));
	close(srcFd);
	close(destFd);

	sprintf(buf,"Y:转账成功，当前余额为:%g",srcAcc.balance);
}